import React, { PureComponent } from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/markPoint';
import 'echarts/lib/component/markLine';
import $ from 'jquery';
import moment from 'moment';


class DeviceTimeSeries extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            inter2: 1,
            times: [],
            dataArrays: []
        }
        this.refreshOption = this.refreshOption.bind(this);
    }

    componentDidMount() {

        const indexes = [
            {
                "code": 1148855702266052600,
                "deviceCode": 1148784465791680500,
                "name": "效率",
                "type": "计算",
                "unit": "%",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702366715900,
                "deviceCode": 1148784465791680500,
                "name": "功率",
                "type": "计算",
                "unit": "kW",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702400270300,
                "deviceCode": 1148784465791680500,
                "name": "流量",
                "type": "计算",
                "unit": "m³/min",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702442213400,
                "deviceCode": 1148784465791680500,
                "name": "参数1",
                "type": "采集",
                "unit": "m³/min",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702479962100,
                "deviceCode": 1148784465791680500,
                "name": "参数2",
                "type": "采集",
                "unit": "m³/min",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702521905200,
                "deviceCode": 1148784465791680500,
                "name": "参数3",
                "type": "采集",
                "unit": "m³/min",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            },
            {
                "code": 1148855702563848200,
                "deviceCode": 1148784465791680500,
                "name": "参数4",
                "type": "采集",
                "unit": "m³/min",
                "memo": null,
                "delete": 0,
                "current": 1,
                "version": 1
            }
        ];

        const indexes3 = indexes.slice(0, 3);
        const config = {
            timeduration: 5,  //单位：s
            legendData: indexes3,
        }

        const times = [];
        const  nows=moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        const beginDay = new Date(nows).getTime();
        
        for (let i = 96; i > 0; i -= 1) {
            times.push(moment(new Date(beginDay - 1000 * config.timeduration * i)).format('mm:ss'));
        }

       
        const dataArrays = [];

        config.legendData.map(item => {
            const lineData = []
            const banseData=800* Math.random();
            const rangedata=100* Math.random();
            for (let i = 96; i > 0; i -= 1) {
                const value = banseData + Math.random() * rangedata;
                lineData.push(value);
            }
            dataArrays.push(lineData);

        });


        this.setState({
            times,
            dataArrays
        });

        const { id } = this.props;
        const that = this;
        echarts.dispose(document.getElementById(id));
        const myChart = echarts.init(document.getElementById(id));
        that.loadChart(myChart, config.legendData);
        that.refreshOption(myChart, config.legendData);

        const inter21 = setInterval(function rand() {
            that.refreshOption(myChart, config.legendData);
        }, config.timeduration * 1000);

        this.setState({ inter2: inter21 });
    }

    componentWillUnmount() {
        const { inter2 } = this.state;
        clearInterval(inter2);
        $(window).unbind('resize', chartIndexAvgResizing)
    }

    refreshOption(myChart, legendData) {

        const { times, dataArrays } = this.state;

        const beginDay = new Date().getTime();
        times.push(moment(new Date(beginDay)).format('mm:ss'));
        times.shift();
        dataArrays.map(item => {
            const value = 800 + Math.random() * 30;
            item.push(value);
            item.shift();
        });

        const seriesArray = [];

        legendData.map((item, index) => {

            seriesArray.push(
                {
                    name: item.name,
                    data: dataArrays[index]
                }
            )
        });


        const dataOption = {
            xAxis: {
                data: times
            },
            series: seriesArray
        };
        myChart.setOption(dataOption);

    }

    loadChart(myChart, legendData) {
        $(window).unbind('resize', chartIndexAvgResizing)
        var option = getChartOption(legendData);
        myChart.setOption(option);
        $(window).bind('resize', { chart: myChart }, chartIndexAvgResizing)
    }

    render() {
        const { id } = this.props;
        return (
            <div id={id} style={{ width: '100%', minHeight: '250px' }} />
        );
    }
}

export default DeviceTimeSeries;


function chartIndexAvgResizing(e) {
    if (e.data.chart) {
        e.data.chart.resize();
    } else {
        return;
    }
}

function getChartOption(legendData) {

    const legendArrays = [];

    const seriesArrays = [];

    const unitArray = [];
    const unitNameArray = [];
    legendData.map((item, index) => {
        legendArrays.push(item.name);

        if(unitArray.indexOf(item.unit)<0)
        {
            unitArray.push(item.unit);
            unitNameArray.push({
                name:item.name,
                unit:item.unit
            })
        }
        
    });

    const colors = ['#5BC0EB', '#E55934', '#9BC53D', '#69306D', '#FCBF49'];
    legendData.map((item, index) => {
        let yindex = unitArray.indexOf(item.unit);
        yindex = index > 0 ? index : 0;
        seriesArrays.push(
            {
                name: `${item.name}`,
                type: 'line',
                smooth: true,
                yAxisIndex: yindex,
                itemStyle: {
                    color: colors[index % colors.length]
                },
                data: []
            },
        );
    });


    const yAxisArray = [];
    unitNameArray.map((item, index) => {
        
        const  unitName='{value}'+item.unit;
        if (index == 0) {
            yAxisArray.push(
                {
                    type: 'value',
                    name: item.name,
                    axisLabel: {
                        formatter: unitName
                    }
                }
            )
        }
        if (index == 1) {
            yAxisArray.push(
                {
                    type: 'value',
                    name:  item.name,
                    position: 'right',
                    axisLabel: {
                        formatter: unitName
                    }
                }
            )
        }
        if (index == 2) {
            yAxisArray.push(
                {
                    type: 'value',
                    name:  item.name,
                    position: 'right',
                    offset: 60,
                    axisLabel: {
                        formatter:unitName
                    }
                }
            )
        }
    });



    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#9ABCC3'
                }
            }
        },
        legend: {
            data: legendArrays
        },
        xAxis: [
            {
                type: 'category',
                data: [],
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: yAxisArray,
        grid: {
            left: 60,
            right: 100
        },
        series: seriesArrays
    };
    return option;
}